package com.lvdp.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.lvdp.dto.Result;
import com.lvdp.dto.UserDTO;
import com.lvdp.entity.Blog;
import com.lvdp.entity.User;
import com.lvdp.mapper.BlogMapper;
import com.lvdp.service.IBlogService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lvdp.service.IUserService;
import com.lvdp.utils.SystemConstants;
import com.lvdp.utils.UserHolder;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Collections;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

import static com.lvdp.utils.RedisConstants.BLOG_LIKED_KEY;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author 辉哥
 * @since 2022-10-31
 */
@Service
public class BlogServiceImpl extends ServiceImpl<BlogMapper, Blog> implements IBlogService {

    @Resource
    private IUserService userService;

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public Result blogDetail(String id) {
        // 查blog
        Blog blog = getById(id);
        if (blog == null) {
            return Result.fail("博客内容为空");
        }
        // blog关联用户
        queryBlogUser(blog);
        // 查询当前用户是否已点赞
        isBlogLiked(blog);
        return Result.ok(blog);
    }

    private void isBlogLiked(Blog blog) {
        // 获取登录用户
        UserDTO user = UserHolder.getUser();
        if (user == null) {
            // 无需要获取是否点赞
            return;
        }
        Long userId = user.getId();
        // 判断userid是否在zset中
        String key = "blog:liked:" + blog.getId();
        Double score = stringRedisTemplate.opsForZSet().score(key, userId.toString());
        blog.setIsLike(score != null);
    }

    @Override
    public Result querHotBlog(Integer current) {
        // 根据用户查询
        Page<Blog> page = query()
                .orderByDesc("liked")
                .page(new Page<>(current, SystemConstants.MAX_PAGE_SIZE));
        // 获取当前页数据
        List<Blog> records = page.getRecords();
        // 查询用户
        records.forEach(this::queryBlogUser);
        return Result.ok(records);
    }

    @Override
    public Result likeBlog(Long id) {
        // 1. 获取当前用户
        Long userId = UserHolder.getUser().getId();
        // 2. 判断当前用户是否已经点赞
        String key = BLOG_LIKED_KEY + id;
        // set 判断存在
//        Boolean member = stringRedisTemplate.opsForSet().isMember(key, userId.toString());
        // zset 判断存在
        Double score = stringRedisTemplate.opsForZSet().score(key, userId.toString());
        // 3. 如果已经点赞，取消点赞 set集合中存在当前用户
//        if (Boolean.TRUE.equals(member)) {
        if (score != null) {
            // 3.1 数据库点赞数量 - 1
            boolean isSuccess = update().setSql("liked = liked - 1")
                    .eq("id", id)
                    .update();
            if (isSuccess) {
                // 3.2 移除用户到Redis的set集合中
//                stringRedisTemplate.opsForSet().remove(key, userId.toString());
                stringRedisTemplate.opsForZSet().remove(key, userId.toString());
            }
        } else {
            // 4. 如果没点赞，则点赞 set集合中不存在当前用户
            // 4.1 数据库点赞数量 + 1
            boolean isSuccess = update().setSql("liked = liked + 1")
                    .eq("id", id)
                    .update();
            if (isSuccess) {
                // 4.2 保存用户到Redis的set集合中 用set只能保证唯一，但是无法排序
//                stringRedisTemplate.opsForSet().add(key, userId.toString());
                // key value score
                stringRedisTemplate.opsForZSet().add(key, userId.toString(), System.currentTimeMillis());
            }
        }
        return Result.ok();
    }

    @Override
    public Result queryBlogLikes(Long id) {
        String key = BLOG_LIKED_KEY + id;
        // 1.查询top5的点赞人数 zrang 0 4
        Set<String> top5 = stringRedisTemplate.opsForZSet().range(key, 0, 4);
        if (top5 == null || top5.isEmpty()) {
            return Result.ok(Collections.emptyList());
        }
        // 2.解析出用户id
        List<Long> ids = top5.stream().map(Long::valueOf).collect(Collectors.toList());
        // 3.根据用户id查询用户 in返回的 不按顺序排列
        String join = StrUtil.join(",", ids);
//        List<UserDTO> userDTOS = userService.listByIds(ids)
        List<UserDTO> userDTOS = userService.query()
                .in("id", ids).last("order by FIELD(id, " + join + ")")
                .list()
                .stream()
                .map(user -> BeanUtil.copyProperties(user, UserDTO.class))
                .collect(Collectors.toList());
        // 4.返回
        return Result.ok(userDTOS);
    }

    /**
     * 在blog中新增用户信息
     *
     * @param blog 博客
     */
    private void queryBlogUser(Blog blog) {
        String key = BLOG_LIKED_KEY + blog.getId();
//        Boolean member = stringRedisTemplate.opsForSet().isMember(key, UserHolder.getUser().getId().toString());
        // zset 判断存在
        Double score = stringRedisTemplate.opsForZSet().score(key, UserHolder.getUser().getId().toString());
        blog.setIsLike(score != null);
        Long userId = blog.getUserId();
        User user = userService.getById(userId);
        blog.setName(user.getNickName());
        blog.setIcon(user.getIcon());
    }
}
